#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <errno.h>
#include <malloc.h>
#include <fcntl.h>
#include <sys/stat.h>

#define INFILE "./in.txt"
#define OUTFILE "./out.txt"
#define MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH)
int main()
{
    int fd_in, fd_out;
    char buf[1024];                 //缓冲区
    memset(buf, 0, sizeof(buf));    //缓冲区清零
    fd_in = open(INFILE, O_RDONLY); //只读方式打开
    if (fd_in < 0)
    {
        fprintf(stderr, "failed to open %s , reason : %s\n", INFILE, strerror(errno));
        exit(-1);
    }
    fd_out = open(OUTFILE, O_WRONLY | O_CREAT | O_TRUNC, MODE);
    if (fd_out < 0)
    {
        fprintf(stderr, "failed to open %s , reason : %s\n", OUTFILE, strerror(errno));
        exit(-1);
    }
    fork(); //派生子进程
    /*父子进程共享此段代码*/
    while (read(fd_in, buf, 2) > 0)
    {
        printf("%d : %s", getpid(), buf);
        sprintf(buf, "%d : Hello World!\n", getpid());
        write(fd_out, buf, strlen(buf));
        sleep(1);
        memset(buf, 0, 1024);
    }
    return 0;
}